package vip.youngboy.freejump.service.bus;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import org.springframework.stereotype.Component;
import vip.youngboy.freejump.domain.bus.BusData;
import vip.youngboy.freejump.domain.bus.BusTableRel;

import java.util.Map;
import java.util.Set;

@Component
public class DefaultBusDataService implements BusDataService {

    @Override
    public String parseAndSaveBusData(JSONObject busData) {
        Set<Map.Entry<String, Object>> entries = busData.entrySet();
        for (Map.Entry<String, Object> entry : entries) {
            //获取表单数据对应的业务对象键
            String boKey = entry.getKey();
            JSONObject value = (JSONObject) entry.getValue();
            parseBusData(value, boKey);
        }

        return null;
    }

    @Override
    public BusData parseBusData(JSONObject busData, String boKey) {
        //通过boKey查找对应的映射关系

        //通过映射关系填充BusData对象

        return null;
    }


    /**
     * 装配busdata数据
     *
     * @param busData     业务数据
     * @param busTableRel 业务表关系对象
     * @return 业务数据
     */
    public BusData assemBusData(JSONObject busData, BusTableRel busTableRel) {
        BusData busDataObj = new BusData();
        Map<String, Object> busDataMap = Maps.newHashMap();
        Set<Map.Entry<String, Object>> entries = busData.entrySet();
        for (Map.Entry<String, Object> entry : entries) {
            String key = entry.getKey();
            Object value = entry.getValue();

            //基础变量
            if (!(value instanceof JSONArray || value instanceof JSONObject)) {
                //TODO 是否需要引入基础变量处理链，用于处理一些脚本信息
                busDataMap.put(key, value);
            }

            //数组
            if (value instanceof JSONArray) {
                //数组
                JSONArray objArr = (JSONArray) value;
                //去掉后面的List
                String tableKey = key.substring(0, key.length() - 4);
                BusTableRel arrTableRel = busTableRel.find(tableKey);
                //找对应表的关系
                for (Object obj : objArr) {
                    JSONObject jsonObject = (JSONObject) obj;
                    busDataObj.addChildren(assemBusData(jsonObject, arrTableRel));
                }
            }

            //对象
            if (value instanceof JSONObject) {
                BusTableRel objRel = busTableRel.find(key);
                busDataObj.addChildren(assemBusData((JSONObject) value, objRel));
            }

        }

        return busDataObj;
    }


    @Override
    public void saveBusData() {

    }

    @Override
    public void loadBusData() {

    }


}
